﻿package net.wangit.adm.user;

import net.wangit.Unit;
import net.wangit.User;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.context.LocalContext;
import net.wangit.support.UnitInterceptor;
import net.wangit.user.AdminUser;
import net.wangit.user.RegisteredUser;
import net.wangit.user.UserFactory;
import net.wangit.user.admin.Admin;
import net.wangit.user.admin.AdminFactory;
import net.wangit.util.ArrayUtil;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;
import net.wangit.view.unit.UnitComponent;

public class UserAuthUI implements UnitInterceptor {

	private static final String DOMAIN = "net.wangit.adm.user.UserAuthUI.domain";
	private static final String USER_ID = "net.wangit.adm.user.UserAuthUI.userid";

	public UserAuthUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String userId = getAndSetUserId();
		if (Checker.isEmpty(userId))
			return "no user was specified!";
		RegisteredUser targetUser = (RegisteredUser) UserFactory
				.getUser(userId);
		if (targetUser == null)
			return "user not found!";
		User user = ac.getVisitor().getUser();
		if (user instanceof AdminUser) {
			Admin a = AdminFactory.getAdmin(user.get("adminid"));
			String orgs[] = a.getOrganizations();
			if (ArrayUtil.find(orgs, targetUser.getOrgId()) < 0)
				return "you could not manage this user!";
		}
		unit.setTitle((new StringBuilder(String.valueOf(((UnitComponent) unit)
				.getTitle()))).append(" - ").append(targetUser.getName())
				.append("(").append(userId).append(")").toString());
		unit.getElement("domain").setDefaultValue(getAndSetDomain());
		unit.getElement("userid").setDefaultValue(userId);
		Tree gTree = (Tree) unit.getElement("groups").getObject();
		unit.getElement("group").setName(gTree.getAction());
		Tree rTree = (Tree) unit.getElement("roles").getObject();
		unit.getElement("role").setName(rTree.getAction());
		unit.getElement("privilege").setName(
				(new StringBuilder(" (")).append(
						targetUser.getPrivileges().size()).append(")")
						.toString());
		return unit.write(ac);
	}

	public static String getAndSetDomain() {
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		return ActionContextHelper.getRequest2Session(ac,
				"user.authorization.domain",
				"net.wangit.adm.user.UserAuthUI.domain", "app");
	}

	public static String getAndSetUserId() {
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		return ActionContextHelper.getRequest2Session(ac, "userid",
				"net.wangit.adm.user.UserAuthUI.userid", null);
	}
}
